package com.heima.createMethods;

import java.lang.invoke.VarHandle;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: Ethan Yankang
 * @Program: 面试必会代码
 * @Date: 2024-08-28 20:23
 **/
public class ThreadPool {
    public static void main(String[] args) {
//        创建一个大小为5的固定数量的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        提交10个任务到线程池里面
        for (int i = 0; i < 10; i++) {
//          executorService.submit(new taskId(i));
            executorService.submit(()->{
                System.out.println("这是"+Thread.currentThread().threadId()+"号线程在执行任务");
            });
        }
        System.out.println("由此可以看出，线程池里面的线程在重复地不断地执行任务！");
//        关闭线程池是必须的
        executorService.shutdown();
    }

    /*
     * @description 因为lamabd表达式里面只能传递最终变量，所以这里动态的变量放在内部类taskId里面去执行
     * @params
     * @return
     */
    static class taskId implements Runnable{
        private int i;
        public taskId(int i){
            this.i=i;
        }
        @Override
        public void run() {
            System.out.println("这是第" +i+"个任务，使用的是线程池里面的"+Thread.currentThread().threadId()+"号线程");
        }
    }
}
